package cn.zc.auth.service.config.handler;

import cn.hutool.json.JSONUtil;
import cn.tools.common.handler.DefaultGlobalExceptionHandler;
import cn.tools.core.base.R;
import cn.tools.core.exception.BizException;
import cn.tools.core.exception.code.ExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: e
 * @date: 2021/12/24
 * @description: 全局异常处理类,继承comm包下的tools-common的全局Handler类，里面以及写好了默认方法
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class AuthExceptionHandler extends DefaultGlobalExceptionHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setStatus(ExceptionCode.NOT_AUTHORITY.getCode());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JSONUtil.parse(R.fail(ExceptionCode.NOT_AUTHORITY)));
        httpServletResponse.getWriter().flush();
    }


}